/**
 * author: Hanflyee  flyee1980@163.com
 * vision: v1.0
 * data: 2009-7-9
 */
package com.flyee.controller.timer{
	
	import com.flyee.service.pool.ObjectCollection;
	import com.flyee.viewer.CharactorViewer;
	import com.flyee.viewer.ComponentViewer;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	/**
	 * 检查人与人深度关系TIMER 
	 */
	public class DepthTimer extends Timer{
		
		public function DepthTimer(delay:Number, repeatCount:int=0){
			super(delay, repeatCount);
		}

		/**
		 * 由N组件将整个场景组件层的深度分割成N+1个区间
		 * 找出每一个区间的起止深度
		 * 用冒泡法检查该区间所有人物的深度关系,并校正
		 */
		public function execute(event : TimerEvent) : void {
			//起始深度
//			var b : int = 0;
//			//结束深度
//			var e : int = 0;
//			for(var i:int=0 ; i<ObjectCollection.componentMap.values().length ; i++){				
//				if(i==0){
//					//第一个组件之前
//					e = this.getComponentDepthByMid(ObjectCollection.currentSceneViewer.componentLayer, ObjectCollection.componentMap.values()[i].mid) - 1;					
//				}else{
//					//N与N+1个组件之间
//					b = e + 1;
//					e = this.getComponentDepthByMid(ObjectCollection.currentSceneViewer.componentLayer, ObjectCollection.componentMap.values()[i].mid) - 1;					
//				}	
//				//检查深度
//				this.checkLayerDepth(ObjectCollection.currentSceneViewer.componentLayer, b, e);			
//			}
//			//最后一个组件之后
//			this.checkLayerDepth(ObjectCollection.currentSceneViewer.componentLayer, e + 1, ObjectCollection.currentSceneViewer.componentLayer.numChildren - 1);
			checkLayerDepth(ObjectCollection.currentSceneViewer.componentLayer, 0, ObjectCollection.currentSceneViewer.componentLayer.numChildren - 1);	
		}
		
		/**
		 * 按MID查找该组件在组件层中的深度,并返回 
		 */
		private function getComponentDepthByMid(container : DisplayObjectContainer, mid : String) : int {
			var vid : String = ObjectCollection.getVidByMid(mid);
			var compUI : ComponentViewer = ObjectCollection.componentViewerMap.get(vid);
			if(container.contains(compUI))
				return container.getChildIndex(compUI);
			else
				return 0;	
		}
		
		/**
		 * 按起止深度检查该区间人与人的深度关系,并校正
		 */
		private function checkLayerDepth(container : DisplayObjectContainer, begin : int, end : int) : void {
			if(begin>=end) return ;
			//冒泡法22检查
			for(var i:int=begin ; i<end ; i++){
				for(var j:int=i+1 ; j<end-1 ; j++){
					var char1 : DisplayObject = container.getChildAt(i);
					var char2 : DisplayObject = container.getChildAt(j);
					if(!(char1 is CharactorViewer) || !(char2 is CharactorViewer)) continue ;
					if(char1.y > char2.y) {
						container.swapChildren(char1, char2);
					}
				}
			}
		}
		
		private function checkCharacterDepth(container : DisplayObjectContainer, viewers : Array) : void {
			
		}
		
	}
}